<template>
	<view class="container">
		<uni-segmented-control :current="currentIndex" :values="items" style-type="text" active-color="#007aff"
			@clickItem="onClickItem" />

		<view v-if="currentIndex === 0">
			<view style="padding-top: 10px;"></view>

			<uni-forms ref="baseForm" :modelValue="dubanForm" border labelWidth="100px" label-position="left">
				<uni-forms-item label="督办事项" required>
					<uni-easyinput type="text" v-model="dubanForm.title" />
				</uni-forms-item>

				<!-- <uni-forms-item label="责任部门" required>
					<picker type="default" :range="departNames" @change="dutyDepartChange">
						<view class="picker-bg">{{dutyDepartNameStr()}}</view>
					</picker>
				</uni-forms-item> -->

				<uni-forms-item label="责任部门" required  label-position="top">
				</uni-forms-item>
				<checkbox-group  @change="dutyDepartsChange">
					<view v-for="(yz,idx) in departNames" :key="idx">
						<view class="check-css"  >
							<checkbox :value="idx">{{yz}}</checkbox>
						</view>
						<view style="padding-bottom: 5px;"></view>
					</view>
				</checkbox-group>

				<!-- 选择单人模板 -->
				<uni-forms-item label="责任人" required>
					<view >
						<button  @click="clickSelectDutyOfficer" class="btn-add" v-if="dubanForm.dutyOfficer.length != 0">{{dubanForm.dutyOfficer[0].name}}</button>
					</view>
					<view >
						<button  @click="clickSelectDutyOfficer" class="btn-add" v-if="dubanForm.dutyOfficer.length == 0">选择负责人</button>
					</view>
				</uni-forms-item>

				<uni-forms-item label="督办内容" required>
					<uni-easyinput type="textarea" @change="chuanci2" @input="chuanci2" v-model="dubanForm.content"
						autoHeight />
				</uni-forms-item>

				<uni-forms-item label="督办时间" required>
					<uni-datetime-picker @click="chuanci()" @change="chuanci2" @maskClick="chuanci2()" type="date"
						return-type="string" v-model="dubanForm.dubanTime" />
				</uni-forms-item>

				<uni-forms-item label="限期时间" required>
					<uni-datetime-picker @click="chuanci()" @change="chuanci2" @maskClick="chuanci2()" type="date"
						return-type="string" v-model="dubanForm.deadTime" />
				</uni-forms-item>

				<uni-forms-item label="督办部门" required>
					<picker type="default" :range="departNames" @change="dubanDepartChange">
						<view class="picker-bg">{{dubanDepartNameStr()}}</view>
					</picker>
				</uni-forms-item>

				<!-- 附件模块 -->
				<uni-forms-item label="附件"></uni-forms-item>
				<view v-for="(item,index) in files.values()" :key="index">
					<view v-if="item.type=='success' && item.size <=1048576">[{{(item.size/1024).toFixed(2)}}KB] {{item.name.substring(0,30)}}
					</view>
					<view v-if="item.type=='success' && item.size >1048576">[{{(item.size/1048576).toFixed(2)}}MB] {{item.name.substring(0,30)}}
					</view>
					<view v-if="item.type!='success'"><i style="color: #51bb88;">上传{{item.progress}}%</i> {{item.name.substring(0,30)}}</view>
				</view>
				<lsj-upload ref="lsjUpload" childId="upload1" height="40px" :size="uploadconfig.size"
					:instantly="uploadconfig.instantly" :formats='uploadconfig.formats' :option="option"
					@change="onChange" @progress="onprogress" @uploadEnd="onuploadEnd">
					<button class="btn-fujian" @click="fuckyou">添加附件</button>

				</lsj-upload>
				<view class="tips">说明：从此上传图片将无法预览，单个文件请控制在100MB以内</view>

				<!-- 图片上传模块 -->
				<uni-forms-item label="图片"></uni-forms-item>
				<uni-row>
					<uni-col :span="8" v-for="(item, idx) in dubanForm.pics" :key="idx">
						<view class="img-res" @click="showBigImg(dubanForm.pics,idx)">
							<image :src="dubanForm.pics[idx]" :key="idx" />
						</view>
					</uni-col>
				</uni-row>
				<button @click="clickSelectPic" class="btn-add">选择图片</button>

				<!-- 选人模块 -->
				<uni-forms-item label="审核人" required></uni-forms-item>
				<view v-for="(item, idx) in dubanForm.auditors" :key="idx">
					<uni-row>
						<uni-col :span="10">
							<view v-if="idx>0" class="step-arrow">
								<uni-icons type="bottom" size="mini" color='#a5eaff'></uni-icons>
							</view>
						</uni-col>
					</uni-row>

					<view class="step">
						<uni-row>
							<uni-col :span="10">
								<view class="step-info-left">{{item.stepName || item.positionName}}</view>
							</uni-col>
							<uni-col :span="14">
								<view class="step-info-right">{{item.name}}</view>
							</uni-col>
						</uni-row>
					</view>
				</view>

				<view style="padding-top: 30px;"></view>
				<button type="primary" @click="clickApply">提交</button>
			</uni-forms>
		</view>
		<view v-if="currentIndex === 1">
			<view v-for="(item, idx) in applyRecord" style="padding-bottom: 10px;" :key="idx">
				<view class="card" @click="seeDetail(idx)">
					<view class="card-title">
						<uni-row>
							<uni-col :span="20">
								<view class="card-title-left">{{item.title}}</view>
							</uni-col>
							<uni-col :span="4">
								<view class="card-title-right">
									<uni-tag text="审核" size="mini" type="warning" v-if="item.sta===0&&item.chexiao==0"></uni-tag>
									<uni-tag text="通过" size="mini" type="primary" v-if="item.sta===1&&item.chexiao==0"></uni-tag>
									<uni-tag text="拒绝" size="mini" type="error" v-if="item.sta===2&&item.chexiao==0"></uni-tag>
									<uni-tag text="撤销" size="mini" type="default" v-if="item.chexiao===1"></uni-tag>
								</view>
							</uni-col>
						</uni-row>
					</view>
					<view class="card-body">
						<view>督办期限：{{item.dubanTime}} ~ {{item.deadTime}}</view>
						<view>督办内容：{{item.content}}</view>
						<view>责任部门：{{listDutyDepartNames(item)}}</view>
						<view>督办部门：{{item.dubanDepart}}</view>
					</view>
					<view class="card-footer">
						<uni-row>
							<uni-col :span="24">
								<view class="card-footer-right">
									{{getFormatedTimeStr(item.createTime)}}
								</view>
							</uni-col>
						</uni-row>
					</view>
				</view>
			</view>

			<uni-load-more :status="moreStatus"></uni-load-more>
		</view>

	</view>
</template>

<script>
	import { websock } from '../../net/websock'
	import moment from 'moment'
	import {uploadconfig} from '../../const'
	import { quchongAuditors } from '../../utils/util'

	export default {
		data() {
			return {
				// 上传参数部分没有事情不要乱动
				uploadconfig,
				option: {
					url: uploadconfig.url,
					name: 'file',
					header: {},
					formData: {}
				},
				formats: uploadconfig.formats,
				instantly: uploadconfig.instantly,
				size: uploadconfig.size,
				files: new Map(),
				// 上传参数部分没有事情不要乱动
				
				currentIndex: 0,
				items: ['发起督办', '督办记录'],
				departNames: [],
				departIds: [],
				// dutyDepartIndex: -1, // 责任部门索引
				dubanDepartIndex: -1, // 督办部门索引
				moreStatus: 'more',
				applyRecord: [],
				auditors: [],
				dutyDeparts: [],
				departList: [],
				dubanForm: {
					title: '', // 督办事项
					dutyOfficer: [], // 责任人
					content: '', // 督办内容
					dubanTime: '', // 督办时间
					deadTime: '', // 限期时间
					pics: [], // 图片
					attaches: [], // 附件
					auditors: []
				}
			}
		},
		async onReady() {
			console.log('zhuanzheng shenqing on ready')

			try {
				this.userInfo = await websock.getUserInfo()

				let departList = await websock.getDepartList()
				for (let i = 0; i != departList.length; i++) {
					if(i>0){
						this.departNames.push(departList[i].name)
						this.departIds.push(departList[i].id)
					}
				}
				console.log('depart list', departList)
				this.departList = departList

				this.auditors = await websock.getAuditors({typ: 6})
				console.log('init auditors', this.auditors)

				this.getAuditors()

				this.getNewestRecord()
			} catch (e) {
				uni.showToast({
					title: e.message
				})
			}
		},
		// 下拉刷新，获取最新的数据
		onPullDownRefresh() {
			console.log('onPullDownRefresh')
			if (this.currentIndex == 0) {
				uni.stopPullDownRefresh()
			} else {
				this.getNewestRecord()
			}
		},
		// 上拉刷新，获取历史数据
		onReachBottom() {
			console.log('onReachBottom')
			if (this.currentIndex == 1) {
				this.getOlderRecord()
			}
		},
		methods: {
			// 附件上传恶心的代码块-------------------------------------------------------------
			// 某文件上传结束回调(成功失败都回调)
			onuploadEnd(item) {
				if (item.type == 'fail') {
					return uni.showToast({title: '上传失败'})}
				try {
					let res = JSON.parse(item.responseText)
					if (res.code !== 0) {
						return uni.showToast({title: res.message || 'error'})}
					this.dubanForm.attaches.push({name: item.name, path: res.data})
					console.log("111",this.dubanForm.attaches)
				} catch (err) {
					uni.showToast({title: err.message})}
				this.$forceUpdate();
			},
			// 上传进度回调
			onprogress(item) {
				this.files.set(item.name,item);// 更新当前状态变化的文件
				this.$forceUpdate();// 强制更新视图
			},
			// 文件选择回调
			onChange(files) {
				this.files = files;// 更新选择的文件 
				this.$forceUpdate();// 强制更新视图
			},
			// 穿刺一击让他们的遮罩层消失
			chuanci(){
				this.$refs.lsjUpload && this.$refs.lsjUpload.hide();
			},
			// 穿刺一击让他们的遮罩层消失
			chuanci2(){
				this.$refs.lsjUpload && this.$refs.lsjUpload.show();
				this.$forceUpdate()
			},
			// 强制重置附件按钮,万一出意外点2次按钮至少可以进去
			fuckyou(){
				this.$refs.lsjUpload && this.$refs.lsjUpload.hide()
				this.$refs.lsjUpload && this.$refs.lsjUpload.show()
				this.$forceUpdate()
			},
			// 附件上传恶心的代码块-------------------------------------------------------------
			// 获取最新的通知
			async getNewestRecord() {
				try {
					if (this.applyRecord.length == 0) {
						let res = await websock.dubandanApplyRecord({
							pageCount: 10
						})
						console.log('getRecordList list empty', res)
						uni.stopPullDownRefresh()
						this.applyRecord = [...res, ...this.applyRecord]
					} else {
						let res = await websock.dubandanApplyRecord({
							greaterThan: this.applyRecord[0].id,
							pageCount: 10
						})
						console.log('getRecordList list not empty', res)
						uni.stopPullDownRefresh()
						this.applyRecord = [...res, ...this.applyRecord]
					}
				} catch (e) {
					uni.showToast({
						title: e.message
					})
				}
			},
			// 获取老的数据
			async getOlderRecord() {
				this.moreStatus = 'loading'
				try {
					if (this.applyRecord.length == 0) {
						console.log('before get list empty')
						let res = await websock.dubandanApplyRecord({
							pageCount: 10
						})
						console.log('getOlderRecord list empty', res)
						this.applyRecord = [...this.applyRecord, ...res]
						if (res.length < 10) {
							this.moreStatus = 'noMore'
						} else {
							this.moreStatus = 'more'
						}
					} else {
						console.log('before get list not empty')
						let res = await websock.dubandanApplyRecord({
							lessThan: this.applyRecord[this.applyRecord.length - 1].id,
							pageCount: 10
						})
						console.log('getOlderRecord list not empty', res)
						this.applyRecord = [...this.applyRecord, ...res]
						if (res.length < 10) {
							this.moreStatus = 'noMore'
						} else {
							this.moreStatus = 'more'
						}
					}
				} catch (e) {
					uni.showToast({
						title: e.message
					})
				}
			},
			
			onClickItem(e) {
				if (this.currentIndex !== e.currentIndex) {
					this.currentIndex = e.currentIndex
				}
			},
			async getAuditors() {
				try {
					this.dubanForm.auditors = []
					let defaultAuditors = this.auditors.slice()
					console.log('dubandan getauditors default auditors', defaultAuditors)
					this.dubanForm.auditors.push(defaultAuditors[0])

					// for (let i = 0; i != this.dutyDeparts.length; i++) {
					// 	let departInfo = this.departList[this.dutyDeparts[i] + 1]
					// 	console.log("duban get auditors depart info", departInfo)

					// 	this.dubanForm.auditors.push({
					// 		name : departInfo.zhijie_lingdao_name,
					// 		positionName : "直接领导",
					// 		sta : "0",
					// 		stepName : departInfo.name + '直接领导',
					// 		uid : departInfo.zhijie_lingdao
					// 	})
					// }

					this.dubanForm.auditors.push(defaultAuditors[1])
					quchongAuditors(this.dubanForm.auditors)

				} catch (err) {
					console.error(err)
					uni.showToast({title: '获取审核人失败'})
				}
			},
			dutyDepartChange(e) {
				console.log('duty depart change', e.detail.value)
				this.dutyDepartIndex = e.detail.value
				// this.getAuditors()
			},
			dutyDepartNameStr() {
				if (this.dutyDepartIndex == -1) return ''
				return this.departNames[this.dutyDepartIndex] || ''
			},
			dubanDepartChange(e) {
				console.log('duban depart change', e.detail.value)
				this.dubanDepartIndex = e.detail.value
			},
			dubanDepartNameStr() {
				if (this.dubanDepartIndex == -1) return ''
				return this.departNames[this.dubanDepartIndex] || ''
			},
			listDutyDepartNames(item) {
				if (!item || !item.dutyInfo) return ''
				let name = ''
				for (let i = 0; i != item.dutyInfo.length; i++) {
					name += item.dutyInfo[i].departName
					if (i != item.dutyInfo.length - 1) {
						name += ','
					}
				}
				return name
			},
			clickSelectDutyOfficer() {
				uni.navigateTo({
					url: '/pages/common/contactSelect?selectedUsers=' + JSON.stringify(this.dubanForm
						.dutyOfficer || []) + '&isSingle=1',
					events: {
						contactList: data => {
							console.log('select auditor', data)
							this.dubanForm.dutyOfficer = data.contactList
						}
					}
				})
			},
			// 选择图片
			clickSelectPic() {
				uni.chooseImage({
					count: 9, //选择图片数
					sourceType: ['camera', 'album'], //从相册还是相机选择
					success: (res) => {
						console.log("ssssss", res)
						for (let path in res.tempFilePaths) {
							uni.uploadFile({
								url: this.uploadconfig.url,
								filePath: res.tempFilePaths[path],
								name: 'file',
								formData: {
									uid: this.userInfo.uid,
									token: store.token
								},
								success: res => {
									try {
										let data = JSON.parse(res.data)
										if (data.code != 0) {
											return uni.showToast({
												title: data.message
											})
										}
										this.dubanForm.pics.push(data.data)
									} catch (e) {
										console.error(e)
										uni.showToast({
											title: '上传图片失败' + e.message
										})
									}
									console.log('success', res)
								},
								fail: (res) => {
									uni.showToast({
										title: '上传图片失败' + res
									})
								},
								complete: () => {
									console.log('uploa file complete')
								}
							})
						}
					}
				})
			},
			clickSelectAuditor() {
				uni.navigateTo({
					url: '/pages/common/contactSelect?selectedUsers=' + JSON.stringify(this.dubanForm.auditors ||
					[]),
					events: {
						contactList: data => {
							console.log('select auditor', data)
							this.dubanForm.auditors = data.contactList
						}
					}
				})
			},
			// 获取格式化时间字符串
			getFormatedTimeStr(stamp, str='MM-DD HH:mm:ss') {
				return moment(stamp).format(str)
			},
			async clickApply() {

				// console.log('duty departs', this.dutyDeparts)

				// for (let i = 0; i != this.dutyDeparts.length; i++) {
				// 	let departInfo = this.departList[this.dutyDeparts[i] + 1]
				// 	console.log(departInfo)
				// }

				if (!this.dubanForm.title) return uni.showToast({
					title: '请输入督办事项'
				})
				if (!this.dubanForm.content) return uni.showToast({
					title: '请输入督办内容'
				})
				if (this.dubanForm.dutyOfficer.length == 0) return uni.showToast({
					title: '请选择责任人'
				})
				if (!this.dubanForm.dubanTime) return uni.showToast({
					title: '请选择督办时间'
				})
				if (!this.dubanForm.deadTime) return uni.showToast({
					title: '请选择截止时间'
				})
				if (this.dubanForm.auditors.length == 0) return uni.showToast({
					title: '请选择审核人'
				})

				if (this.dutyDeparts.length == 0) return uni.showToast({
					title: '请选择责任部门'
				})

				// if (this.dutyDepartIndex == -1) return uni.showToast({
				// 	title: '请选择责任部门'
				// })

				if (this.dubanDepartIndex == -1) return uni.showToast({
					title: '请选择督办部门'
				})

				let auditors = []
				for (let i = 0; i != this.dubanForm.auditors.length; i++) {
					auditors.push({uid: this.dubanForm.auditors[i].uid, stepName: this.dubanForm.auditors[i].stepName || this.dubanForm.auditors[i].positionName})
				}

				let dutyInfo = []
				for (let i = 0; i != this.dutyDeparts.length; i++) {
					let departInfo = this.departList[this.dutyDeparts[i] + 1]
					console.log(departInfo)
					dutyInfo.push({
						departId: departInfo.id,
						departName: departInfo.name,
						departLingdao: departInfo.zhijie_lingdao,
						departLingdaoName: departInfo.zhijie_lingdao_name
					})
				}

				try {
					await websock.dubandanApply({
						title: this.dubanForm.title,
						content: this.dubanForm.content,
						// dutyDepartment: this.departNames[this.dutyDepartIndex],
						dutyInfo,
						dubanDepartment: this.departNames[this.dubanDepartIndex],
						dubanTime: this.dubanForm.dubanTime,
						deadTime: this.dubanForm.deadTime,
						dutyOfficer: this.dubanForm.dutyOfficer[0].uid,
						pics: this.dubanForm.pics,
						attaches: this.dubanForm.attaches || [],
						auditors
					})

					uni.showToast({
						title: '申请成功'
					})

					this.dubanForm = {
						title: '', // 督办事项
						dutyOfficer: [], // 责任人
						content: '', // 督办内容
						dubanTime: '', // 督办时间
						deadTime: '', // 限期时间
						pics: [], // 图片
						attaches: [], // 附件
						auditors: []
					}

					this.dubanDepartIndex = -1
					// this.dutyDepartIndex = -1

					this.currentIndex = 1
					this.getNewestRecord()
				} catch (err) {
					uni.showToast({
						title: err.message
					})
				}
			},
			async revertApply(idx) {
				try {
					await websock.revertDubandanApply({
						id: this.applyRecord[idx].id
					})
					this.applyRecord[idx].sta = 4
				} catch (err) {
					console.error(err)
					uni.showToast({
						title: err.message || 'error'
					})
				}
			},
			//点击放大图片
			showBigImg(imgurl, cur) {
				uni.previewImage({
					current: cur,
					loop: true,
					urls: imgurl,
				})
			},
			// 查看详情
			seeDetail(idx) {
				uni.navigateTo({
					url: `/pages/task/dubanApplyDetail?id=${this.applyRecord[idx].id}`
				})
			},
			dutyDepartsChange(e) {
				console.log('duty departs change', e)
				this.dutyDeparts = e.detail.value
				this.getAuditors()
			}
		}
	}
</script>

<style>
	@import '../common/common.css';
</style>
